package main.java.modules.alipay.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;

import main.java.common.constants.Constants;
import main.java.common.model.Product;
import main.java.modules.alipay.service.AlipayService;

@Controller
@RequestMapping("alipay")
public class AlipayController {
	private static final Logger logger = LoggerFactory.getLogger(AlipayController.class);
	@Autowired
	private AlipayService alipayService;
	
	@RequestMapping("/index")
	public String index() {
		return "alipay/index";
	}
	
	@RequestMapping("/pcPay")
	public String pcPay(Product product,ModelMap map) {
		logger.info("电脑支付");
		String form = alipayService.aliPayPc(product);
		map.addAttribute("form", form);
		return "alipay/pay";
		
	}
	
	@RequestMapping("/qcPay")
	public String qcPay(Product product, ModelMap map) {
		logger.info("二维码支付");
		String message = alipayService.aliPay(product);
		if(Constants.SUCCESS.equals(message)) {
			String img = "../qrcode/" + product.getOutTradeNo() + ".png";
			map.addAttribute("img", img);
		}
		return "alipay/qcpay";
	}
	
	@RequestMapping(value="pay", method=RequestMethod.POST)
	public void alipay_notify(HttpServletRequest request, HttpServletResponse response) {
		String message = "success";
		Map<String, String> params = new HashMap<String, String>();
		//取出所有参数验证签名
		Enumeration<String> parameterNames = request.getParameterNames();
		while(parameterNames.hasMoreElements()) {
			String parameterName = parameterNames.nextElement();
			params.put(parameterName, request.getParameter(parameterName));
		}
		//校验签名
		boolean signVerified = false;
		try {
			signVerified = AlipaySignature.rsaCheckV1(params, Configs.getAlipayPublicKey(), "UTF-8");
			
		}catch(AlipayApiException e) {
			e.printStackTrace();
			message = "failed";
		}
		
		if(signVerified) {
			logger.info("支付宝验证签名成功");
			//若参数中的appid和填入的appid不同，则异常通知
			if(!Configs.getAppid().equals(params.get("app_id"))) {
				logger.info("与付款时的appid不同，异常通知");
				message = "failed";
			} else {
				String outtradeno = params.get("out_trade_on");
				//校验订单单号的金额是否与数据库中的一样
				String status = params.get("trade_status");
				//若为等待用户付款
				if(status.equals("WAIT_BUYER_PAY")) {
					logger.info(outtradeno + "订单正在等待用户付款");
				} else if(status.equals("TRADE_CLOSED")) { //若订单超时关闭
					logger.info(outtradeno + "订单已关闭");
				} else if(status.equals("TRADE_SUCCESS") || status.equals("TRADE_FINISHED")) {
					logger.info("支付宝：" + outtradeno + "订单付款成功");
				} else {
					//根据业务需求填写代码
				}
			}
		} else {
			message = "failde";
			logger.info("验证签名失败");
		}
		try {
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			out.write(message.getBytes());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
